﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class UIManager : MonoBehaviour
{
    private static UIManager instance;
    public static UIManager Instance => instance;
    private Dictionary<string, GameObject> panels = new Dictionary<string, GameObject>();
    private void Awake()
    {
        instance = this;
    }
    private void Start()
    {
        ShowPanel<LoginPanel>();
    }
    /// <summary>
    /// 显示面板/获取面板
    /// </summary>
    /// <typeparam name="T">BasePanel</typeparam>
    /// <returns>T : BasePanel</returns>
    public T ShowPanel<T>() where T : BasePanel
    {
        string panelName = typeof(T).Name;
        if (panels.ContainsKey(panelName))
        {
            return panels[panelName].GetComponent<T>();
        }
        GameObject panel = Instantiate(Resources.Load<GameObject>("UI/Panel/" + panelName), transform);
        panels.Add(panelName, panel);
        T t = panel.GetComponent<T>();
        t.ShowMe();
        return t;
    }

    /// <summary>
    /// 隐藏面板
    /// </summary>
    /// <typeparam name="T">BasePanel</typeparam>
    public void HidePanel<T>() where T : BasePanel
    {
        string panelName = typeof(T).Name;
        if (!panels.ContainsKey(panelName))
        {
            return;
        }
        GameObject panelObj = panels[panelName];
        BasePanel panel = panelObj.GetComponent<T>();
        if (panel.fadeOn)
        {
            panel.HideMe(() =>
            {
                Destroy(panelObj);
                panels.Remove(panelName);
            });
        }
        else
        {
            panel.HideMe();
            Destroy(panelObj);
            panels.Remove(panelName);
        }
    }
}
